package com.gzxw.mogublog.xo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzxw.mogublog.commons.entity.Blog;
import com.gzxw.mogublog.commons.entity.Tag;
import com.gzxw.mogublog.utils.StringUtils;
import com.gzxw.mogublog.xo.mapper.BlogMapper;
import com.gzxw.mogublog.xo.mapper.TagMapper;
import com.gzxw.mogublog.xo.service.BlogService;
import com.gzxw.mogublog.xo.service.TagService;
import com.gzxw.mogublog.xo.vo.TagVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Autowired
    private BlogService blogService;

    @Override
    public IPage<Tag> getList(TagVO tagVO) {

        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(tagVO.getKeyword())) {
            tagQueryWrapper.like("content", tagVO.getKeyword().trim());
        }
        if (StringUtils.isNotEmpty(tagVO.getOrderByAscColumn())) {
            tagQueryWrapper.orderByAsc(StringUtils.underLine(new StringBuffer(tagVO.getOrderByAscColumn())).toString());
        } else if (StringUtils.isNotEmpty(tagVO.getOrderByDescColumn())) {
            tagQueryWrapper.orderByDesc(StringUtils.underLine(new StringBuffer(tagVO.getOrderByDescColumn())).toString());
        } else {
            tagQueryWrapper.orderByDesc("sort");
        }

        tagQueryWrapper.eq("status", 1);

        Page<Tag> page = new Page<>();
        page.setCurrent(tagVO.getCurrentPage());
        page.setSize(tagVO.getPageSize());


        return this.page(page, tagQueryWrapper);
    }

    @Override
    public String add(TagVO tagVO) {
        Tag tag = new Tag();

        // 判断当前标签是否存在
        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.eq("status", 1);
        tagQueryWrapper.eq("content", tagVO.getContent());
        Tag tempTag = this.getOne(tagQueryWrapper);

        if (tempTag != null) {
            return "该标签已经存在";
        }

        tag.setContent(tagVO.getContent());
        tag.setStatus(1);
        tag.setSort(tagVO.getSort());
        tag.setClickCount(0);
        boolean save = this.save(tag);
        // 删除redis中的博客标签
        return save ? "添加成功" : "添加失败";
    }

    @Override
    public String edit(TagVO tagVO) {

        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.eq("uid", tagVO.getUid());
        tagQueryWrapper.eq("status", 1);
        Tag tag = this.getOne(tagQueryWrapper);

        // 判断编辑后的内容是不是和数据库里的重复
        if (tag != null && !tag.getContent().equals(tagVO.getContent())) {
            QueryWrapper<Tag> tagWrapper = new QueryWrapper<>();
            tagWrapper.eq("content", tagVO.getContent());
            tagWrapper.eq("status", 1);
            Tag one = this.getOne(tagWrapper);
            if (one != null) {
                return "该标签已经存在!";
            }
        }
        tag.setContent(tagVO.getContent());
        tag.setUpdateTime(new Date());
        tag.setSort(tagVO.getSort());
        boolean edit = this.updateById(tag);
        // 删除和标签相关的博客缓存

        // 删除Redis中的BLOG_TAG
        return edit ? "更新成功" : "更新失败";
    }

    @Override
    public String deleteBatch(List<TagVO> tagVOList) {
        List<String> uidList = new ArrayList<>();

        tagVOList.forEach(item -> {
            uidList.add(item.getUid());
        });

        Collection<Tag> tags = this.listByIds(uidList);

        // 判断这些标签下是否有博客
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq("status", 1);
        blogQueryWrapper.in("tag_uid", uidList);
        int count = blogService.count(blogQueryWrapper);
        if (count > 0) {
            return "该标签下还有博客!";
        }

        tags.forEach(item -> {
            item.setStatus(0);
            item.setUpdateTime(new Date());
        });

        this.updateBatchById(tags);

        // 删除和标签相关的博客缓存

        // 删除Redis中的BLOG_TAG

        return "删除成功";
    }

    @Override
    public String stickTag(TagVO tagVO) {

        // 根据tagVo.getUid从数据库中查询出来
        Tag tag = this.getById(tagVO.getUid());
        // 查出sort最大的标签
        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.eq("status", 1);
        tagQueryWrapper.orderByDesc("sort");
        tagQueryWrapper.last("limit 1");
        Tag maxSortTag = this.getOne(tagQueryWrapper);
        // 将sort最大的标签查出来+1赋值给当前标签
        int sortCount = maxSortTag.getSort();

        if (StringUtils.isEmpty(maxSortTag.getUid())) {
            return "参数输入有误!";
        }

        if (tag.getUid().equals(maxSortTag.getUid())) {
            return "该标签已经在顶端";
        }
        tag.setSort(sortCount + 1);
        tag.setUpdateTime(new Date());
        // 更新当前tag
        this.updateById(tag);
        return "顶置成功";
    }

    @Override
    public String tagSortByClickCount() {

        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.eq("status", 1);
        tagQueryWrapper.orderByDesc("click_count");
        List<Tag> list = this.list(tagQueryWrapper);

        list.forEach(item -> {
            item.setSort(item.getClickCount());
            item.setUpdateTime(new Date());
        });
        this.updateBatchById(list);
        // 删除Redis中的BLOG_TAG
        return "操作成功";
    }

    @Override
    public String tagSortByCite() {

        // 每个标签都有一个引用量
        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.eq("status", 1);
        List<Tag> tagList = this.list(tagQueryWrapper);

        // 查询所有的博客
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq("status", 1);
        // 还要查询发布了的博客
        blogQueryWrapper.eq("is_publish", "1");
        // 过滤content
        blogQueryWrapper.select(Blog.class, i -> !i.getProperty().equals("content"));
        List<Blog> blogList = blogService.list(blogQueryWrapper);

        // 使用map保存 key：标签id  value：引用量
        Map<String, Integer> citeMap = new HashMap<>();

        // 为每个标签初始化引用量
        tagList.forEach(item -> {
            citeMap.put(item.getUid(), 0);
        });

        // 设置每个标签的引用量
        blogList.forEach(item -> {
            String tagUid = item.getTagUid();
            if (citeMap.get(tagUid) != null) {
                citeMap.put(tagUid, citeMap.get(tagUid) + 1);
            } else {
                citeMap.put(tagUid, 0);
            }
        });

        // 将引用量赋值给sort
        tagList.forEach(item -> {
            item.setSort(citeMap.get(item.getUid()));
            item.setUpdateTime(new Date());
        });

        // 更新数据库中的sort
        this.updateBatchById(tagList);
        // 删除Redis中的BLOG_TAG

        return "操作成功";
    }

    @Override
    public List<Tag> getHotTag(Integer hotTagCount) {

        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
        Page<Tag> page = new Page<>();
        tagQueryWrapper.eq("status",1);
        tagQueryWrapper.orderByDesc("sort");
        tagQueryWrapper.orderByDesc("click_count");

        page.setCurrent(1);
        page.setSize(hotTagCount);

        IPage<Tag> pageList = this.page(page, tagQueryWrapper);

        return pageList.getRecords();
    }
}
